#include "LSocket.h"
#include "cocos2d.h"

LSocket::LSocket() : m_fd(0)
{
}


LSocket::~LSocket(void)
{
	Close();
#ifdef WIN32
	WSACleanup();
#endif
}

bool LSocket::InitSock() {
#ifdef WIN32
	WSADATA wsadata;
	unsigned short winsock_version=MAKEWORD( 1, 1 );
	if(WSAStartup(winsock_version,&wsadata))
	{
		return false;
	}
#endif
	return true;
}

bool LSocket::Connect(const char *ip, unsigned int port)
{
	SOCKET sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(sClient == INVALID_SOCKET)
    {
		return false;
    }

	SOCKADDR_IN addrServ;
    addrServ.sin_family = AF_INET;
    addrServ.sin_addr.S_un.S_addr = inet_addr(ip);
    addrServ.sin_port = htons(port);
    if(connect(sClient, (sockaddr *)&addrServ, sizeof(sockaddr)) == SOCKET_ERROR)
    {
		return false;
    }
	this->m_fd = sClient;
	return true;
}

void LSocket::Send(const char *pcBuf, unsigned int uiLen)
{
	if (this->m_fd == 0)
		return;
	CCLOG("send-size:[%d]", uiLen);
	unsigned int tLen = 0;
	while (tLen < uiLen) {
		tLen += send(this->m_fd, pcBuf, uiLen - tLen, 0);
	}
}

void LSocket::SendLenAndData(const char *pcBuf, unsigned int uiLen)
{
	uint32_t nlen = htonl(uiLen);
	Send((const char*)&nlen, 4);
	Send(pcBuf, uiLen);
}

int LSocket::Recv(char *pcBuf, unsigned int uiLen)
{
	if (this->m_fd == 0)
		return -1;
	int tLen = recv(this->m_fd, pcBuf, uiLen, 0);
	if (tLen <= 0)
		Close();
	CCLOG("recv-size:[%d]", tLen);
	return tLen;
}

void LSocket::Close()
{
	if (m_fd)
		closesocket(m_fd);
	m_fd = 0;
}
